<template>
    <div class="page-wrapper">
        <BreadMenu />
        <div style="height:96%; background:#fff; ">
            <div style="width:80%; height:100%; margin:0 auto; padding-top:var(--hPadding);">
                <FlexForm ref="myForm" :form="form" :rules="rules" :fieldList="fieldList" :opt="formOpt" @submit="handleSubmit" />
                    <TableWrapper :hasControls="false" :pageInfo="pageInfo" :sourceData="inspectionList" :column="column" :noPadding="true" :total="inspectionTotal" @search="handleSearch" />
                    <div style="margin:var(--sPaddding) 0;">
                        <div class="flex-btn opacity" @click="handleSelection">{{ isAllCheck ? '取消全选' : '全选' }}</div>
                    </div>
                    <div style="margin:var(--mPadding) 0;">
                        <div class="flex-btn large" @click="checkSubmit">
			            	<i class="ri-sticky-note-add-line"></i>保存
			            </div>
                    </div>

            </div>
        </div>   
	</div> 
</template>

<script setup>
    import { ref, watch, reactive, onMounted, computed, h } from 'vue';
    import { useRoute, useRouter } from 'vue-router';
    import { getTplInspectionList, getTplCode } from '@/api/tpl.js'; 
    import { getCycleList } from '@/api/cycle.js';
	import { getGroupList, delGroup } from '@/api/group.js';
    import { getObjectList } from '@/api/object.js';
    import { addOrUpdateTask } from '@/api/task.js'
    import { ElMessage, ElPopconfirm, ElInput, ElCheckbox  } from 'element-plus' 
    import TableWrapper from '@/components/TableWrapper/index.vue';
    import ConfirmDel from '@/components/ConfirmDel.vue';
    import BreadMenu from '@/components/BreadMenu.vue';
    import FlexForm from '@/components/FlexForm.vue';
    import { formatDateTime } from '@/utils/date';
    import { downloadExcel } from '@/utils/excel.js';
    import Icon1 from '@/assets/icon-add.png';
	import Icon2 from '@/assets/icon-refresh.png';

    const route = useRoute();
    const router = useRouter();
    const pageInfo = reactive({ page:1, pageSize:10 });
    const formOpt = { labelPosition:'top', layout:'inline', colNum:4  };
    const form = reactive({
        startTime:null,
        endTime:'',
        groupId:'',
        targetId:'',
    });
    const myForm = ref();
    // 确保选中当天，取当天的最后一个小时为基准
    const todayDate = new Date();
    todayDate.setHours(0, 0, 0, 0);
    const todayTimestamp = todayDate.getTime();
    const rules = reactive({
        startTime:[{ required:true, message:'请选择推送时间',  trigger:'blur' }],
        endTime:[{ required:true, message:'请选择任务截止时间',  trigger:'blur' }],
        groupId:[{ required:true, message:'请选择对象分组', trigger:'blur' }],
        targetId:[{ required:true, message:'请选择巡检对象', trigger:'blur' }],
    });
    const fieldList = ref([
        { type:'date', label:'开始推送时间', placeholder:'请选择时间', paramKey:'startTime', clearable:true, checkDisabledDate:(date)=>{
            return date.getTime() < todayTimestamp;
        } },
        { type:'date', label:'任务截止时间', placeholder:'请选择时间', paramKey:'endTime', clearable:true, checkDisabledDate:(date)=>{
            const timestamp = form.startTime ? form.startTime.getTime() : todayTimestamp;
            return date.getTime() < timestamp;
        }},
		{ type:'select', payload:[], total:0, label:'巡检对象分组', extraOption:{ label:'未分组', key:'-1' },  hasPagination:true, size:'large', paramKey:'groupId', labelKey:'groupId', labelName:'groupName', clearable:false  },
		{ type:'select', payload:[], total:0, label:'巡检对象', size:'large', hasPagination:true, search:fetchObjectList, paramKey:'targetId', labelKey:'targetId', labelName:'targetName', clearable:true  }
	]);
    const cycleList = ref([]);
    const groupList = ref([]);
    const groupTotal = ref(0);
    const objectList = ref([]);
    const objectTotal = ref(0);
    const inspectionList = ref([]);
    const inspectionTotal = ref(0);
    const rows = ref([]);
    const isAllCheck = computed(()=>{
        return inspectionList.value.length && rows.value.length === inspectionList.value.length
    })
    const column = [
        { label:'是否巡检', hasTpl:true, width:'80px', render:(row, index)=>{
            return {
                com:h(ElCheckbox, { modelValue:rows.value.includes(row.itemTargetId), onChange:(checked, e)=>{ 
                    if ( checked ) {
                        rows.value.push(row.itemTargetId);
                    } else {
                        let arr = rows.value.filter(i=> i !== row.itemTargetId);
                        rows.value = arr;
                    } 
                }})
            }
        }},
        { label:'巡检项名称', prop:'itemName'  },
        { label:'标准与要求', prop:'itemNormAndDemand' },
        { label:'参数记录', hasTpl:true, render:row=>{
            return { com:h('div', null, row.needValueRemark === 1 ? `${row.valueName}(${row.valueUnit})` : '--' ) };
        }},
        { label:'检查方法及工具', prop:'checkWayAndTool' },
        { label:'巡检周期', hasTpl:true, render:row=>{ let obj = cycleList.value.filter(i=>i.cycleId === row.cycleId)[0] || {};  return { com:h('span', null, obj.cycleName || '--' ) }} },
    ];
    watch(()=>form.startTime, ()=>{
        // 监听推送时间
        if ( form.startTime && form.endTime ) {
            if ( form.startTime.getTime() > form.endTime.getTime() ) {
                form.endTime = null;
            }
        }
    });
    watch(()=>form.groupId, ()=>{
        fetchObjectList({ page:1, pageSize:10, groupId:form.groupId })
    })
    watch([groupList, objectList], ()=>{
        fieldList.value[2] = { ...fieldList.value[2], payload:groupList.value, total:groupList.value.length };
        fieldList.value[3] = { ...fieldList.value[3], payload:objectList.value, total:objectTotal.value };
    })
    // 更新巡检对象的巡检项表
    watch(()=>form.targetId, ()=>{
        
        fetchInspectionList();
    })
    const fetchGroupList = (params)=>{
		// 实际的axios请求;
		params = params || { page:1, pageSize:999 };
		getGroupList(params)
		.then(res=>{
			if ( res.data.code === 200 ){
				groupList.value = res.data.data;
			}
		})
	}
    function fetchObjectList(params) {
		// 实际的axios请求;
		params = params || { page:1, pageSize:10 };
	    getObjectList(params)
		.then(res=>{
			if ( res.data.code === 200 ){
		        objectList.value = res.data.data;
				objectTotal.value = res.data.total;
			}
		})
	}
    const fetchInspectionList = (params)=>{
	    // 实际的axios请求;
	    params = params || { };
        params.targetId = form.targetId;
        params.page = pageInfo.page;
        params.pageSize = pageInfo.pageSize;
        rows.value = [];
	    getTplInspectionList(params, true)
	    .then(res=>{
	    	if ( res.data.code === 200 ){
	    	    inspectionList.value = res.data.data;
	    		inspectionTotal.value = res.data.total;
	    	}
	    })
	};
    const fetchCycleList = ()=>{
		// 实际的axios请求;
		getCycleList({ page:1, pageSize:999 })
		.then(res=>{
			if ( res.data.code === 200 ){
				cycleList.value = res.data.data;
			}
		})
	};
    const handleSearch = (optional)=>{
	    // // 调用请求接口
	    fetchInspectionList({ ...optional });
	}
    const handleSelection = ()=>{
        if ( isAllCheck.value ) {
            rows.value = [];
        } else {
            rows.value = inspectionList.value.map(i=>i.itemTargetId);
        }
    }
    const handleSubmit = ()=>{
        if ( rows.value.length ) {
            new Promise((resolve, reject)=>{
                getTplCode()
                .then(res=>{
                    if ( res.data.code === 200 ) {
                        resolve(res.data.data);
                    }
                })
            })
            .then(code=>{
                if ( !code ) return;
                let params = { groupId:form.groupId, targetId:form.targetId, missionCode:code, itemTargetIds:[...rows.value] };
                if ( form.startTime ) {
                    params.startTime = formatDateTime(form.startTime, false) + ' 00:00:00';
                }
                if ( form.endTime ) {
                    params.endTime = formatDateTime(form.endTime, false) + ' 23:59:59';
                }   
                addOrUpdateTask(params, false)
                .then(res=>{
                    if ( res.data.code === 200 ) {
                        ElMessage({
                            type:'success',
                            message:'手动生成巡检任务成功'
                        });
                        router.push('/inspectionTask');
                    }
                })
            })
            
        } else {
            ElMessage.error('请勾选巡检项！');
        }
    }
    const checkSubmit = ()=>{
        if ( myForm.value.handleSubmit && typeof myForm.value.handleSubmit === 'function' ) {
            myForm.value.handleSubmit();   
        }
    }

    // 请求一个
    onMounted(()=>{
        fetchGroupList();
        fetchCycleList();
       
    })
</script>